package com.kangtu.demologinweimeng.controller;

import com.kangtu.demologinweimeng.config.SiteOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * @program: demo-weix-pay
 * @description: MainController
 * @author: 亮子说编程
 * @create: 2021-03-11 15:13
 **/

@Controller
@Slf4j
public class MainController {

    @Autowired
    private SiteOptions siteOptions;

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/")
    public String index() {
        return "index";
    }

    @GetMapping(value = "/detail")
    public String detail() {
        return "detail";
    }

    @ResponseBody
    @PostMapping(value = "/upload")
    public Object upload(@RequestParam("editormd-image-file") MultipartFile file) {
        HashMap<String, Object> map = new HashMap<>();

        //-- check
        if(file.isEmpty()){
            map.put("success", 0);
            map.put("message", "上传图片失败了");
            map.put("url", "");

            return map;
        }

        //--
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        UUID uuid = UUID.randomUUID();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String newName = uuid.toString() + suffix;

        //--
        String filePath = siteOptions.getLocation() + "/storage/thumbnails/_signature/";
        File dest = new File(filePath + newName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
            log.info("上传成功");
            map.put("success", 1);
            map.put("message", "上传成功了");
            map.put("url", "/storage/thumbnails/_signature/"+newName);
            return map;

        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        map.put("success", 0);
        map.put("message", "上传图片失败了");
        map.put("url", "");

        return map;
    }
}
